package com.wsz.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.sql.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class CreateTableUtils {
    /**
     * 实体类转换Mysql数据库表结构
     *   2022-10-23 13:14
     */
        public static String getTableSql( String tableName,Class cla){
            Boolean idFlag = false;
            StringBuffer stringBuffer = new StringBuffer ();
            Field[] fields = cla.getDeclaredFields();
            stringBuffer.append ("CREATE TABLE `"+tableName+"` (");
            for (Field field : fields) {

                if (!Modifier.isStatic (field.getModifiers ()) && !"currentUser".equals (field.getName ())){
                    if("id".equals(getName(field.getName()))) idFlag = true;
                    stringBuffer.append ("\n").append (getName(field.getName ())+" ");
                    stringBuffer.append (getMysqlColunmType (field.getType ()));
                    if(!"id".equals(getName(field.getName ()))) stringBuffer.append (" NULL DEFAULT NULL ,");
                    else stringBuffer.append(" NOT NULL AUTO_INCREMENT ,");
                }
            }
            if(idFlag) stringBuffer.append("\n").append("PRIMARY KEY (`id`) ");
            stringBuffer.delete (stringBuffer.length ()-1,stringBuffer.length ());
            stringBuffer.append ("\n").append (")ENGINE=InnoDB\n" +
                    "DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ;");

            return stringBuffer.toString();

        }


    /**
     * 获取Mysql列属性
         * @param cls
         *
         */
        public static String getMysqlColunmType(Class cls){
            String clsName = cls.toString ();
            if (cls == Date.class){
                return  "datetime";
            }
            if (cls == Boolean.class){
                return "tinyint(1)";
            }
            if (cls == BigDecimal.class || cls == Double.class){
                return  "decimal(12,2)";
            }
            if (cls == Integer.class||cls == Long.class || clsName.equals ("int") || clsName.equals ("long")){
                return  "int";
            }
            if (cls == Map.class || cls == List.class){
                return "varchar(2000) CHARACTER SET utf8mb4 ";//是map类型或list类型则装好为varchar（2000）
            }
            if(cls == String.class) {
                return "varchar(255) CHARACTER SET utf8mb4 ";
            }
            else {
                if(validateTableNameExist(cls.getName())){
                    MysqlUtils.CreateTable(cls.getName(),cls);
                }
                return "varchar(255) CHARACTER SET utf8mb4";
            }
        }

        /**
         * 获取属性名称转换数据库列
         * 驼峰转换
         * @param name
         * @return
         */
        private  static String getName(String name){
            StringBuffer stringBuffer = new StringBuffer ();
            for (char c : name.toCharArray ()) {
                if (Character.isUpperCase (c)){
                    stringBuffer.append ("_");
                    stringBuffer.append (Character.toLowerCase (c));
                }else{
                    stringBuffer.append (c);
                }
            }
            return stringBuffer.toString ();
        }

    public static boolean validateTableNameExist(String tableName) {
        Connection con = JdbcUtils.getConnection();
        try {
            DatabaseMetaData metaData = con.getMetaData();

            ResultSet resultSet = metaData.getTables(null, null, tableName, new String[]{"TABLE"});

            boolean execute = resultSet.next();

            if(execute) {
                return false;
            }else {
                return true;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }
}
